package cn.mrcode.fd.blog.controller;

import cn.mrcode.fd.blog.buutil.FieldCheckUtil;
import cn.mrcode.fd.blog.buutil.ResultJsonUtil_back;
import cn.mrcode.fd.blog.common.BaseController;
import cn.mrcode.fd.blog.common.BusConstant;
import cn.mrcode.fd.blog.dto.BlogResult;
import cn.mrcode.fd.blog.dto.ConQQDto;
import cn.mrcode.fd.blog.dto.RegistDto;
import cn.mrcode.fd.blog.dto.account.RegisterResData;
import cn.mrcode.fd.blog.entity.LoginInfo;
import cn.mrcode.fd.blog.entityCu.BlogConfigCu;
import cn.mrcode.fd.blog.entityCu.UserCu;
import cn.mrcode.fd.blog.services.IAccountService;
import cn.mrcode.fd.blog.services.IBlogConfigService;
import cn.mrcode.fd.blog.services.IUserService;
import cn.mrcode.fd.plugin.security.exception.AuthcException;
import cn.mrcode.fd.plugin.security.helper.SecurityHelper;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;

/**
 * 账户处理
 *
 * @author : zhuqiang
 * @version : V1.0
 * @date : 2015/12/16 22:03
 */
@RequestMapping("/account")
@Controller
public class AccountController extends BaseController {
    private static Logger LOGGER = LoggerFactory.getLogger(AccountController.class);
    @Autowired
    private IAccountService iAccountService;
    @Autowired
    private IUserService iUserService;
    @Autowired
    private IBlogConfigService iBlogConfigService;

    @RequestMapping("/logout")
    public String logout(Model model) {
        SecurityHelper.logout();
        return "redirect:/";
    }

    @RequestMapping("/login")
    public String login(String account, Model model) {
        if (account != null) {
            model.addAttribute("account",account);
        }
        return "/login";
    }

    @RequestMapping(value = "/login/submit", produces = "application/json;charset=utf-8")
    @ResponseBody
    public String login(String account, String password, Model model) throws Exception {
        if (StringUtils.isBlank(account) || StringUtils.isBlank(password)) {
            return ResultJsonUtil_back.fail("账户或密码为空", null);
        }
        try {
            SecurityHelper.login(account, password);
            UserCu user = iUserService.findUserCu(account);
            BlogConfigCu blogConfigCu = iBlogConfigService.findBlogConfigCu(user.getId());
            user.setBlogConfig(blogConfigCu);
            session.setAttribute(BusConstant.SessionKey.USER_INFO, user);
        } catch (AuthcException e) {
            e.printStackTrace();
            return ResultJsonUtil_back.fail("账户或密码错误", null);
        }
        JSONObject result = new JSONObject();
        String redirect = String.format("%s%s/article/list", getDomain(), account);
        result.put("redirect", redirect);
        return ResultJsonUtil_back.success(String.format("%s,欢迎您回来!,2秒后自动跳转...<a href=\"%s\" class=\"alert-link\">点我跳转</a>", getUser().getName(), redirect), result);
    }

    @RequestMapping("/register")
    public String register() {
        return "/register";
    }

    /**
     * 异步校验账户是否可注册
     *
     * @param account
     *
     * @throws Exception
     */
    @RequestMapping(value = "/isregister/account")
    @ResponseBody
    public void isRegAccount(String account) throws Exception {
        if (StringUtils.isBlank(account)) {
            response.getWriter().write("false");
            return;
        }

        String accountInfo = FieldCheckUtil.isMatches("account", account);
        if(accountInfo != null){
            response.getWriter().write("false");
            return;
        }else{
            boolean isCanUsed_account =  iAccountService.isCanUsed_account(account);
            if(!isCanUsed_account){
                response.getWriter().write("false");
                return;
            }
        }

        response.getWriter().write("true");
    }

    /**
     * 异步校验邮箱是否被占用
     *
     * @param email
     *
     * @throws Exception
     */
    @RequestMapping(value = "/isregister/email")
    @ResponseBody
    public void isRegEmail(String email) throws Exception {
        if (StringUtils.isBlank(email)) {
            response.getWriter().write("false");
            return;
        }

        LoginInfo _eloginInfo = iAccountService.findByEmail(email);
        if (_eloginInfo != null) {
            response.getWriter().write("false");
            return;
        }
        response.getWriter().write("true");
    }

    @RequestMapping(value = "/register/submit", produces = "application/json;charset=utf-8")
    @ResponseBody
    public BlogResult registerSubmit(RegistDto registDto) {
        registDto = registDto == null ? new RegistDto() : registDto;
        HashMap<String, String> errMap = new HashMap<String, String>();
        String account = registDto.getAccount();
        String email = registDto.getEmail();
        String password = registDto.getPassword();

        String accountInfo = FieldCheckUtil.isMatches("account", account);
        if(accountInfo != null){
            return new BlogResult(false,accountInfo);
        }
        String email1Info = FieldCheckUtil.isMatches("email", email);
        if (email1Info != null) {
            return new BlogResult(false,email1Info);
        }
        String passwordInfo = FieldCheckUtil.isMatches("password", password);
        if (passwordInfo != null) {
            return new BlogResult(false,passwordInfo);
        }

        RegisterResData register = iAccountService.register(registDto);

        if(!register.isSuccess()){
            return new BlogResult(false,register.getInfo());
        }
        return new BlogResult(true,"",account);
    }


    /**
     * 尝试使用openid登录，登录失败则需要绑定新账户
     * @param openid
     * @return
     */
    @RequestMapping(value = "/con/qq/login/{openid}", produces = "application/json;charset=utf-8")
    @ResponseBody
    public String qq_login(@PathVariable String openid){
        UserCu userCu = iAccountService.qq_login(openid);
        if(userCu != null){ //登录成功
            session.setAttribute(BusConstant.SessionKey.USER_INFO, userCu);
            return ResultJsonUtil_back.success("登录成功",null);
        }else {
            return ResultJsonUtil_back.fail("登录失败！",null);
        }
    }
    /**
     *
     * @param type 1 : 新账户绑定。 2: 已有账户绑定
     * @return
     */
    @RequestMapping(value = "/con/qq/bdaccount/{type}", produces = "application/json;charset=utf-8")
    @ResponseBody
    public String qqLoginbdAccount(@PathVariable int type, ConQQDto conQQDto){
        String openid = conQQDto.getOpenid();
        String nickname = conQQDto.getNickname();
        String figureurl_2 = conQQDto.getFigureurl_2();
        String account = conQQDto.getAccount();

        if(StringUtils.isBlank(openid)){
            return ResultJsonUtil_back.fail("QQ可能未被正常授权，请重新尝试登录后再绑定",null);
        }

        String accountInfo = FieldCheckUtil.isMatches("account", account);
        if(1 == type){
            if(accountInfo != null){
                return ResultJsonUtil_back.fail(accountInfo,null);
            }else{
                boolean isCanUsed_account =  iAccountService.isCanUsed_account(account);
                if(!isCanUsed_account){
                    return ResultJsonUtil_back.fail("该账户不能注册[可能被占用/禁用]",null);
                }
            }
            String noMd5Password = iAccountService.insertCon_QQ_1(conQQDto, BusConstant.Sysuser.SYS_USER_ID);
            UserCu userCu = iAccountService.qq_login(openid);
            if(userCu != null){ //登录成功
                session.setAttribute(BusConstant.SessionKey.USER_INFO, userCu);
                JSONObject resData = new JSONObject();
                resData.put("account",userCu.getAccount());
                resData.put("password",noMd5Password);
                resData.put("blog","http://www.mrcode.cn/"+account);
                return ResultJsonUtil_back.success("绑定并登录成功",resData);
            }else{
                return ResultJsonUtil_back.fail("绑定登录失败，请刷新页面尝试自动登录",null);
            }
        }else{
            if(accountInfo != null){
                return ResultJsonUtil_back.fail(accountInfo,null);
            }
            String password = conQQDto.getPassword();
            String passwordInfo = FieldCheckUtil.isMatches("password", account);
            if(passwordInfo != null){
                return ResultJsonUtil_back.fail(passwordInfo,null);
            }
            try {
                SecurityHelper.login(account, password);
                String info = iAccountService.updateCon_QQ_2(conQQDto, BusConstant.Sysuser.SYS_USER_ID);
                if(info != null){
                    SecurityHelper.logout();
                    return ResultJsonUtil_back.fail(info,null);
                }
                UserCu userCu = iAccountService.qq_login(openid);
                if(userCu != null) { //登录成功
                    session.setAttribute(BusConstant.SessionKey.USER_INFO, userCu);
                    return ResultJsonUtil_back.success("绑定并登录成功",null);
                }
            } catch (AuthcException e) {
                return ResultJsonUtil_back.fail("账户或密码错误",null);
            } catch (Exception e) {
                SecurityHelper.logout();
                return ResultJsonUtil_back.fail("服务错误，请稍后刷新重试",null);
            }
        }
        return "";
    }
}
